/*
重庆时时彩 五星
*/
cc.Class({
    extends: cc.Component,

    properties: {
        //标头
        labTopTitle:{
            default: null,
            type: cc.Label
        },
        //投注信息
        labShowAmount:{
           default: null,
           type: cc.Label 
        },

        //说明
        labDec:{
           default: null,
           type: cc.RichText 
        },

        edMutipleNum:{
            default:null,
            type:cc.EditBox
        },

        edIssueNum:{
            default:null,
            type:cc.EditBox
        },

        ndLabTip:{
            default:null,
            type:cc.Node
        },
        
         prLine:{
            default:null,
            type:cc.Prefab
        },
        
        //选择球根目录
        betContent:{
            default:[],
            type:cc.Node
        },

        //投注单根目录
        ndBetPanle:{
            default: null,
            type: cc.Node
        },

        //选择球
        tgRedBall:{
            default: null,
            type: cc.Prefab
        },

        //选择玩法按钮列表
        tgAnySelList:{
            default:[],
            type:cc.Toggle
        },

        //机选清空切换按钮
        tgSelect:{
            default:null,
            type:cc.Toggle
        },

        //红球图片
        spRedBall:{
            default: null,
            type: cc.SpriteFrame
        },

        //红球放大
        spBigRedBall:{
            default: null,
            type: cc.Sprite
        },

        tgIsStop:{
            default:null,
            type:cc.Toggle
        },

                    //用于显示放大效果的位置
        ndBallContent:{
            default:null,
            type:cc.Node
        },

        ndAddAward:{
            default:[],
            type:cc.Node
        },

        BASEMONEY:2,//基础投资
        _rules:[],//规则
        _nums:[],//数值
        _betToggleList:[],//球指针列表
        _selRedBall:[],//选择球数字列表
        _decContents:[],//说明列表

        _isMiss:false,//是否开启遗漏
        _lotteryID:0,//彩种id
        _totalisuse:0,//总期数
        _curMoney:0,
        _curBetNum:0,
        _curPage:0,
        _isStops:-1,//追号到截止
        _betManage:null
    },

     //重置初始值
    initReset:function(){
        if(this._isMiss )
        {
            this._betManage.showMissArry(this._betToggleList,this._lotteryID,this._lotteryID + this._rules[this._curPage].toString());
        }
    },

    //外部传参
    init:function(lotteryid){
        this._lotteryID = lotteryid;  
        this._isStops = -1;
        this.initConfig();
    },

          //是否中奖后停止追号
    onIsStops:function(toggle, customEventData){
        if(toggle.isChecked == true)
        {
            this._isStops = 0;
        }
        else
        {
            this._isStops = -1;
        }
    },

    initConfig:function(){
        this._rules = [DEFINE.LOTTERYRULESSC.ZHI_FIVE,DEFINE.LOTTERYRULESSC.TONG_FIVE];
        this.names = ["五星直选","五星通选"];
        this._nums = ["0","1","2","3","4","5","6","7","8","9"]; 
         this._decContents = [
            "<color=#ffffff>每位至少选1个号码,按位猜对全部开奖号码即中</c><color=#fcd346>10万元</color>",
            "<color=#ffffff>每位至少选1个号码，按位猜对开奖号码可中</c><color=#fcd346>20~20440元</color>",
        ];
        this._totalisuse = 87;
        for(var i=0;i<5;i++)
        {
            var arry = [];
            this._selRedBall.push(arry);
        }
        this._offsetX = 65;
        this._offsetY =580;
        this._isStops =-1;
    },

     // use this for initialization
    onLoad: function () {
         this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            console.log('sscFiveStarPage node  TOUCH_END');
            var contentRect = this.ndBetPanle.getBoundingBoxToWorld();
            var touchLocation = event.getLocation();
            contentRect.x = contentRect.x -20;
            contentRect.width = 1080;
            contentRect.height = 1585;//错误：暂未找到原因，当垂直滚动该值会变大
            if(cc.rectContainsPoint(contentRect, touchLocation) == false){//关闭投注界面
                cc.log("bet betPanel close");
                this.onClose();
            }
        }, this);

       this.initPanel();
       this._betManage = cc.find("Canvas").getChildByName("ChatRoomPage").getChildByName("BetManage").getComponent("BetManage");
    },

    showAddAward:function(data){
        for(var i=0;i<data.length;i++)
        {
            var codestr = data[i].PlayCode.toString();
            var code = codestr.substring(codestr.length-2,codestr.length);
            var index = this._rules.indexOf(code); 
            if(index != -1)
            {
                var icode = parseInt(code);
                this.ndAddAward[icode-1].active = true;
            }
        }
    },

     //初始化场景信息
    initPanel:function(){   
        for(var i=0;i<5;i++)
        {
            var arry = [];
            for(var j = 0;j<this._nums.length;j++)
            {      
                var ball = cc.instantiate(this.tgRedBall);
                ball.getComponent('Bet_toggle_ball').init({
                    num: this._nums[j],
                    miss: ""
                });
    
                var checkEventHandler = new cc.Component.EventHandler();
                checkEventHandler.target = this.node; 
                checkEventHandler.component = "sscFiveStarPage"
                checkEventHandler.handler = "onClickCallback";
                checkEventHandler.customEventData = {num:j,type:i};
                ball.getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
                this.betContent[i].addChild(ball);
                arry.push(ball);
                
                //事件监听
                //当手指在目标节点区域内离开屏幕时。
                ball.on(cc.Node.EventType.TOUCH_END, function (event) {
                    cc.log("sscFiveStarPage toggle  red TOUCH_END_end");
                    this.spBigRedBall.node.y = 10000;
                },this);

                //当手指在目标节点区域外离开屏幕时。
                ball.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {
                    cc.log("sscFiveStarPage toggle  red TOUCH_CANCEL_end");
                    this.spBigRedBall.node.y = 10000;
                },this);

                //当手指触摸到屏幕时。
                ball.on(cc.Node.EventType.TOUCH_START, function (event) {
                    cc.log("sscFiveStarPage toggle  red TOUCH_START_end");
                    if(!ball.active)
                        return;
                    var curTg = event.getCurrentTarget();
                    var pos = curTg.getPosition();
                    var type = curTg.getComponent(cc.Toggle).checkEvents[0].customEventData.type;
                    this.spBigRedBall.node.getChildByName("labnum").getComponent(cc.Label).string = curTg.getComponent('Bet_toggle_ball').getNum();
                    this.spBigRedBall.node.x = pos.x+60;
                    this.spBigRedBall.node.y = pos.y+ this.ndBallContent.y+130-((type)*350);
                    this.spBigRedBall.node.active = true;
                },this);

                //当鼠标在目标节点在目标节点区域中移动时，不论是否按下。
                ball.on(cc.Node.EventType.MOUSE_MOVE, function (event) {
                    //cc.log("move");
                    event.stopPropagation();
                    var curTg = event.getCurrentTarget();
                    var contentRect = curTg.getBoundingBoxToWorld();
                    var touchLocation = event.getLocation();
                    if(cc.rectContainsPoint(contentRect, touchLocation) == false){
                        cc.log("sscFiveStarPage toggle  red MOUSE_MOVE_end"); 
                        this.spBigRedBall.node.y = 10000;
                    }  
                },this);

                //当手指在屏幕上目标节点区域内移动时。
                ball.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
                    var curTg = event.getCurrentTarget();
                    var contentRect = curTg.getBoundingBoxToWorld();
                    var touchLocation = event.getLocation();
                    if(cc.rectContainsPoint(contentRect, touchLocation) == false){
                        cc.log("sscFiveStarPage toggle  red TOUCH_MOVE_end"); 
                        this.spBigRedBall.node.y = 10000;
                    }  
                },this);
            }
            this._betToggleList.push(arry);   
        }
        for(var i=0;i<this.tgAnySelList.length;i++)
        {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "sscFiveStarPage"
            checkEventHandler.handler = "onSelPageCallBack";
            checkEventHandler.customEventData = {
                name:this.names[i],
                pageID:i,
                decContent:this._decContents[i]
            };
            this.tgAnySelList[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }
        //初始选择第一个小界面
        var temp = this.tgAnySelList[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
        this.onSelPageCallBack(this.tgAnySelList[0],temp);
    },

     onSelPageCallBack:function(toggle, customEventData){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this.labTopTitle.string = customEventData.name;
            this.labDec.string = customEventData.decContent;
            this._curPage = customEventData.pageID;
            this.clearCurSel();

            if(this._isMiss )
            {
                this._betManage.showMissArry(this._betToggleList,this._lotteryID,this._lotteryID + this._rules[this._curPage].toString());
            }
        }  
    },

    onClickCallback:function(toggle, customEventData){
        var num = customEventData.num;
        var type = customEventData.type;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this._selRedBall[type].push(num);
        }
        else
        {
             Utils.removeByValue(this._selRedBall[type],num);
        }
        this.updateTgSelect();
        this.checkBet();
    },

    //设置金额
    setMoney:function(mon){
        this._curMoney = mon;
    },

    //得到金额
    getMoney:function(){
        return this._curMoney;
    },

    //设置注数
    setBetNum:function(num){
        this._curBetNum = num;
    },

    //得到注数
    getBetNum:function(){
        return this._curBetNum;
    },

    //设置期数
    setIssueNum:function(num){
        if(this._totalisuse >= parseInt(num))
        {
            this.edIssueNum.string = num;
        }
        else
        {
            ComponentsUtils.showTips("最大只能选择87期");
            this.edIssueNum.string = this._totalisuse.toString();
        }
        this.checkBet();
    },

    //得到期数
    getIssueNum:function(){
        var num = parseInt(this.edIssueNum.string);
        if(isNaN(num)){ 
            return 1;
        }else{
            return num;
        }        
    },

       //手动期数
    onEditBoxIssueChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("倍数不能为空！");
        }

        var amount = parseInt(editbox.string);
       if(isNaN(amount) || amount<=0 ){
            editbox.string = "1";
        }
  
       this.setIssueNum(editbox.string);
    },

    //设置倍数
    setMutipleAmount:function(mutiple){
         this.edMutipleNum.string = mutiple;
         this.checkBet();
    },

    //获取当前倍数
    getMutipleAmount:function(){
        var amount = parseInt(this.edMutipleNum.string);
        if(isNaN(amount)){ 
            return 1;
        }else{
            return amount;
        }        
    },

    //手动倍数
    onEditBoxMutipleChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("倍数不能为空！");
        }

        var amount = parseInt(editbox.string);
        if(isNaN(amount) || amount > 999 || amount<=0 ){
            editbox.string = "1";
        }
  
        this.checkBet();
    },

    //显示投注信息
    setShowAmount:function(mut,bet){
        var issue = this.getIssueNum();
        var money = mut*bet*this.BASEMONEY*issue;
        this.setMoney(money);
        this.setBetNum(bet);
        this.labShowAmount.string = "共"+bet+"注"+ mut +"倍"+ issue + "期"+ money+"元";
    },

    //检查倍数
    checkBet:function(){
        var bet = 0;
        var betTemp = 1;
        for(var i=0;i<5;i++)
        {
            betTemp = this._selRedBall[i].length*betTemp;
        }
        bet = betTemp;
        var muiple = this.getMutipleAmount();
        this.setShowAmount(muiple,bet);
    },

    //重置界面
    clearAllBetRecord:function(){
        this.clearCurSel();
    },
    //清空当前选择
    clearCurSel:function(){
        for(var i=0;i<this._selRedBall.length;i++)
        {
            this._selRedBall[i].length = 0;
        }

        for(var i=0;i<this._betToggleList.length;i++)
        {
            for(var j=0;j<this._betToggleList[i].length;j++)
            {
                this._betToggleList[i][j].getComponent(cc.Toggle).isChecked = false;
            }
        }
        this._isStops = -1;
        this.tgIsStop.getComponent(cc.Toggle).isChecked = false;
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
        this.setIssueNum(1);
        this.setMutipleAmount(1);
        this.checkBet();
    },
   
    //机选
    randomSelectCallBack:function(){
        this.clearCurSel();
        for(var i=0;i<5;i++)
        {
            var randomArray = Utils.getRandomArrayWithArray(this._betToggleList[i], 1);
            if(randomArray.length>0)
            {
                randomArray[0].getComponent(cc.Toggle).isChecked = true;
                var temp = randomArray[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
                this.onClickCallback(randomArray[0],temp);
            }
        }    
        return true;
    },

  //选择清空切换
    onSelectCallBack:function(toggle){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this.randomSelectCallBack();
        }
        else
        {
            this.clearCurSel();
        }
    },

    updateTgSelect:function(){
        for(var i=0;i<this._selRedBall.length;i++)
        {
            if(this._selRedBall[i].length > 0)
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = true;
                return;
            }
        }
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
    },

    //投注信息组合
    dataToJson:function(){
        var objs = [];
        var obj = new Object(); 
        obj.PlayCode = parseInt(this._lotteryID + this._rules[this._curPage]); 
        var nums = "";
        var num = "";
        for(var i=0;i<5;i++)
        {
            num = "";
            Utils.sortNum(this._selRedBall[i]);
            for(var j=0;j<this._selRedBall[i].length;j++)
            {
                if(num != "")
                    num += ",";
                    num += this._selRedBall[i][j];
            }
            if(nums != "")
                nums += "|";
            nums += num;
        }

        var arry = [];
        var numArrays = {
            "Multiple":this.getMutipleAmount(),
            "Bet":this.getBetNum(),
            "isNorm":1,
            "Number":nums
        };
        arry.push(numArrays);
        obj.Data = arry;
        objs.push(obj);
        var json = JSON.stringify(objs);
        cc.log("提交订单：" + json);
        return json;
    },
     //追号组合支付
    chasePay:function(){
        var recv = function(ret){
            ComponentsUtils.unblock(); 
            if(ret.Code === 0)
            {
                var len = ret.Data.length;
                if(len != this.getIssueNum())
                {
                    this.setIssueNum(len);
                    this.setShowAmount();
                }
                var obj = new Object(); 
                obj.Stops = this._isStops;
                obj.IsuseCount = len;
                obj.BeginTime = ret.Data[0].BeginTime;
                obj.EndTime = ret.Data[len-1].EndTime;
                var arry = [];
                for(var i=0;i<ret.Data.length;i++)
                {
                    var numArrays = {
                        "IsuseID":ret.Data[i].IsuseCode,
                        "Amount": LotteryUtils.moneytoClient(this.getMoney()/this.getIssueNum()),//每期金额
                        "Multiple":this.getMutipleAmount(),//每期总倍数
                    };
                    arry.push(numArrays);
                }
                obj.Data = arry;
                var json = JSON.stringify(obj);

                var data = {
                    lotteryId:this._lotteryID,//彩种id
                    dataBase:this.dataToJson(),//投注信息
                    otherBase:json,//追号
                    money:this.getMoney(), 
                    buyType: this.getIssueNum() >1?1:0,//追号
                }

                window.Notification.emit("BET_ONPAY",data);
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
        }.bind(this);
        var data = {
            Token:User.getLoginToken(),
            LotteryCode:this._lotteryID,
            Top:this.getIssueNum(),
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETADDTOISUSE, data, recv.bind(this),"POST");   
        ComponentsUtils.block();    
    },

       //付款
    onPayBtn:function(){
        if(this.getMoney() <= 0)
            return;
        
        if(this.getIssueNum()<=1)
        {
            var data = {
                lotteryId:this._lotteryID,//彩种id
                dataBase:this.dataToJson(),//投注信息
                otherBase:"",//追加
                money:this.getMoney(),
                buyType: 0,//追号
            }
            window.Notification.emit("BET_ONPAY",data);
        }
        else
        {
            this.chasePay();
        }
    },

     onClose:function(){
        window.Notification.emit("BET_ONCLOSE","");
    },

    onNextPage:function(){
        window.Notification.emit("BET_NEXTPAGE",1);
    },

    onLastPage:function(){
        window.Notification.emit("BET_NEXTPAGE",-1);
    },


    onMiss:function(toggle){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this._isMiss = true;
            this._betManage.showMissArry(this._betToggleList,this._lotteryID,this._lotteryID + this._rules[this._curPage].toString());
        }    
        else
        {
            this._isMiss = false;
            this._betManage.setMissArry(false,this._betToggleList,"");
        }
    },
    
});

